﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

namespace Assets.Content.Scripts.DateBase
{
    public static class AccessPlayerDate
    {
        public static int ID;
        private static readonly string Path = @"C:\Users\Administrator\Documents\Game\PlayerDate\"; //存档路径
        private const string PlayerInfo = @"\PlayerInfo.txt"; //存档文件名       

        public static DirectoryInfo[] GetFileFolder()//获取PlayerData文件夹下的存档个数
        {
            DirectoryInfo[] folder = null;
            if (Directory.Exists(Path))
            {
                var direction = new DirectoryInfo(Path);
                folder = direction.GetDirectories();
            }
            return folder;
        }

        public static void SavePlayerDate(PlayerData playerData)//存储
        {
            var jsonStr = JsonUtility.ToJson(playerData);

            try
            {
                ID = GetFileFolder().Length;
                var tempPath = "";

                if (GetFileFolder().Length == 0)
                {
                    tempPath = Path + "1-" + playerData.Name; //存储格式: 默认路径 + 玩家名字的文件夹 + PlayerInfo.txt
                }
                else
                {
                    var _int = Convert.ToInt32(GetFileFolder()[ID - 1].Name.Split('-')[0]);
                    _int ++;
                    tempPath = Path + _int.ToString() + "-" + playerData.Name;
                }

                if (!Directory.Exists(tempPath))
                    Directory.CreateDirectory(tempPath);

                var file = new FileStream(tempPath + PlayerInfo, FileMode.OpenOrCreate);
                var sw = new StreamWriter(file);
                sw.WriteLine(jsonStr);
                sw.Close();
                file.Close();
            }
            catch (IOException ex)
            {
                Debug.LogError("错误信息: " + ex.Message);
                return;
            }
        }

        public static PlayerData LoadPlayerDate()//读取
        {
            //TODO 将名称改为顺序制  Done
            var files = GetFileFolder();
            var fs = new FileStream(files[ID].GetFileSystemInfos()[0].FullName, FileMode.Open);
            var sw = new StreamReader(fs);

            var jsonStr = sw.ReadLine();
            PlayerData playerData = JsonUtility.FromJson<PlayerData>(jsonStr);
            sw.Close();
            fs.Close();
            return playerData;
        }
    }
}